package com.dcbeida.activity.zyff;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.MessageQueue;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.dcbeida.MyApplication;
import com.dcbeida.R;
import com.dcbeida.activity.BaseActivity;
import com.dcbeida.activity.CaptureActivity;
import com.dcbeida.activity.CommonListActivity;
import com.dcbeida.activity.hospital.HospitalActivity;
import com.dcbeida.activity.sign.SignQrCodeActivity;
import com.dcbeida.activity.store.StoreActivity;
import com.dcbeida.adapter.StoreAdapter;
import com.dcbeida.bean.CouponDrug;
import com.dcbeida.bean.CpreSendDrug;
import com.dcbeida.bean.DrugCode2Info;
import com.dcbeida.bean.DrugCodeInfo;
import com.dcbeida.bean.DrugCodeItem;
import com.dcbeida.bean.HospitalBean;
import com.dcbeida.bean.Image;
import com.dcbeida.bean.SignStatusEnum;
import com.dcbeida.callback.PhotoCallBack;
import com.dcbeida.listern.DialogListener;
import com.dcbeida.utils.CameraUtil;
import com.dcbeida.utils.Constants;
import com.dcbeida.utils.DialogUtils;
import com.dcbeida.utils.GetPhotoFromAlbum;
import com.dcbeida.utils.GifSizeFilter;
import com.dcbeida.utils.PutAliyObject;
import com.dcbeida.utils.Utils;
import com.dcbeida.utils.permission.AndPermission;
import com.dcbeida.utils.permission.PermissionListener;
import com.dcbeida.utils.permission.Rationale;
import com.dcbeida.utils.permission.RationaleListener;
import com.dcbeida.widget.PhotoViewShow;
import com.dcbeida.widget.TipDialog;
import com.dcbeida.widget.scanitem.DrugScanView;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.filter.Filter;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.Bind;
import butterknife.OnClick;

import static com.dcbeida.utils.Constants.PERMISSION_CAMERA;
import static com.dcbeida.utils.Constants.PERMISSION_WRITE_EXTERNAL_STORAGE;
import static com.dcbeida.utils.Constants.REQUEST_CODE_CHOOSE;

public class CarePlanActivity extends BaseActivity implements CarePlanContract.View {


    @Bind(R.id.img_back)
    ImageView img_back;

    @Bind(R.id.et_name)
    EditText et_name;

    @Bind(R.id.et_tel)
    EditText et_tel;

    @Bind(R.id.et_idcard)
    EditText et_idcard;

    @Bind(R.id.ll_yymc)
    LinearLayout ll_yymc;

    @Bind(R.id.tv_yymc)
    TextView tv_yymc;

    @Bind(R.id.et_jzys)
    EditText et_jzys;

    @Bind(R.id.add_Group)
    LinearLayout add_Group;

    @Bind(R.id.ns_view)
    NestedScrollView ns_view;

    @Bind(R.id.tv_empty_memo)
    TextView tv_empty_memo;

    @Bind(R.id.lin_ga_card)
    LinearLayout lin_ga_card;

    @Bind(R.id.lin_yhq)
    LinearLayout lin_yhq;
    @Bind(R.id.tv_type)
    TextView tv_type;

    @Bind(R.id.tv_qh)
    TextView tv_qh;
    @Bind(R.id.tv_count)
    TextView tv_count;
    @Bind(R.id.tv_yxq)
    TextView tv_yxq;
    @Bind(R.id.lin_add_drugs)
    LinearLayout lin_add_drugs;
    @Bind(R.id.lin_other_type)
    LinearLayout lin_other_type;
    @Bind(R.id.tv_he)
    TextView tv_he;
    @Bind(R.id.tv_end_confim)
    TextView tv_end_confim;
    @Bind(R.id.yg_list)
    DrugScanView yg_list;
    @Bind(R.id.tv_scan)
    TextView tv_scan;
    @Bind(R.id.picList)
    LinearLayout picList;
    @Bind(R.id.ll_tel_type)
    LinearLayout ll_tel_type;
    @Bind(R.id.tv_tel_type)
    TextView tv_tel_type;
    @Bind(R.id.ll_credit_type)
    LinearLayout ll_credit_type;
    @Bind(R.id.tv_crdeit_type)
    TextView tv_crdeit_type;

    @Bind(R.id.tv_sign_status)
    TextView tv_sign_status;

    @Bind(R.id.recyclerview)
    RecyclerView recyclerview;
    public Handler iHandler;
    private int telType = 0;
    private int creditType=0;//默认0
    
    private CarePlanContract.Present mPresent;
    private ArrayList<String> imgUrl;//服务器图片地址
    private String localUrl = "";//选取的本地图片url
    private List<String> obtainPathResult;//本地图片地址
    private boolean isConfirm = false;
    private StoreAdapter storeAdapter;
    private static final String[] requestPermissions = {
            PERMISSION_CAMERA,
            PERMISSION_WRITE_EXTERNAL_STORAGE
    };

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_care_plan;
    }

    @Override
    public void setData() {
        super.setData();
        tv_empty_memo.post(new Runnable() {
            @Override
            public void run() {
                int height = ns_view.getBottom() - add_Group.getTop();
                LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) tv_empty_memo.getLayoutParams();
                layoutParams.height = height;
                tv_empty_memo.setLayoutParams(layoutParams);
            }
        });
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initparam();
        initRecyClerView();
        addMessageHandler();
    }

    private void initRecyClerView() {
        obtainPathResult = new ArrayList<String>();
        imgUrl = new ArrayList<String>();
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerview.setLayoutManager(layoutManager);
        //如果可以确定每个item的高度是固定的，设置这个选项可以提高性能
        recyclerview.setHasFixedSize(true);
        storeAdapter = new StoreAdapter(mContext);
        storeAdapter.setDefaultDrawable(R.drawable.songhuodan3);
        recyclerview.setAdapter(storeAdapter);
        storeAdapter.setOnItemClickListener(new StoreAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (position == storeAdapter.mUris.size()) {
                    //权限申请
                    AndPermission.with(mContext)
                            .requestCode(100)
                            .permission(requestPermissions)
                            .rationale(rationaleListener)
                            .send();
                } else {
                    //传递当前点击的图片的位置、图片路径集合
                    Bundle bundle = new Bundle();
                    bundle.putInt("position", position);
                    bundle.putStringArrayList("mImages", imgUrl);
                    showActivity(PhotoViewShow.class, bundle);
                }
            }

        });

        storeAdapter.setOnItemDelClickListener(new StoreAdapter.OnRecyclerViewItemDelClickListener() {
            @Override
            public void onItemDelClick(View view, int position) {
                obtainPathResult.remove(position);
                imgUrl.remove(position);
                storeAdapter.setData(imgUrl);
            }
        });

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        AndPermission.onRequestPermissionsResult(requestCode, permissions, grantResults, listener);
    }

    private PermissionListener listener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, List<String> grantPermissions) {
            Matisse.from(mContext)
                    .choose(MimeType.ofAll(), false)
                    .countable(true)
                    .capture(true)
                    .captureStrategy(new CaptureStrategy(true, "com.dcbeida.utils.GifSizeFilter"))
                    .maxSelectable(Constants.MAX_IMAGE_SIZE - imgUrl.size())
                    .addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
                    .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                    .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                    .thumbnailScale(0.85f)
                    .imageEngine(new GlideEngine())
                    .forResult(REQUEST_CODE_CHOOSE);
        }

        @Override
        public void onFailed(int requestCode, List<String> deniedPermissions) {

        }
    };

    private RationaleListener rationaleListener = new RationaleListener() {
        @Override
        public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
            rationale.resume();
        }
    };

    private void initparam() {
        mPresent = new CarePlanPresenter(this, this);

    }

    @Override
    public void showError(String message) {
        TipDialog tipDialog = new TipDialog(mContext).setMessage(message);
        tipDialog.show();
    }

    @Override
    public void showData(CouponDrug info) {
        tv_end_confim.setText(getString(R.string.qrtj));
        tv_scan.setText(getString(R.string.zysm));
        isConfirm = true;
        if (!TextUtils.isEmpty(info.getTruename())) {
            et_name.setText(info.getTruename());
        }

        if (!TextUtils.isEmpty(info.getPhonenum())) {
            et_tel.setText(info.getPhonenum());
        }

        if (!TextUtils.isEmpty(info.getDoctorname())) {
            et_jzys.setText(info.getDoctorname());
        }

        if (!TextUtils.isEmpty(info.getIdcardnum())) {
            et_idcard.setText(info.getIdcardnum());
        }

        if (!TextUtils.isEmpty(info.getHospitalname())) {
            tv_yymc.setText(info.getHospitalname());

        }


       if(getString(R.string.bjga).equals(info.getType())){
           tv_type.setText(getString(R.string.bjga)+"赠药券");
       }else if(getString(R.string.yxbl).equals(info.getType())){
           tv_type.setText(getString(R.string.yxbl)+"赠药券");
           lin_other_type.setVisibility(View.GONE);
       }else  if(getString(R.string.shfz).equals(info.getType())){
           tv_type.setText(getString(R.string.shfz)+"赠药券");
           lin_other_type.setVisibility(View.GONE);
       }else{
           tv_type.setText(info.getType()+"赠药券");
           lin_other_type.setVisibility(View.GONE);
       }
        tv_empty_memo.setText("请进行赠药扫码");
        lin_yhq.setVisibility(View.VISIBLE);
        tv_qh.setText("券号：" + info.getCouponcode());
        tv_count.setText(info.getUsestatus() == 0 ? "1" : "2");
        if (info.getUsestatus() == 1) {
            picList.setVisibility(View.VISIBLE);
        }
        tv_yxq.setText("有效期：" + info.getEffecttime().replace(".000Z", "") + " 至 "
                + info.getExpirationtime().replace(".000Z", ""));

        if (info.getList() != null && !info.getList().isEmpty()) {
            lin_add_drugs.setVisibility(View.VISIBLE);
            setDrugData(info.getList());
        }

    }

    @Override
    public void showAddDrug(DrugCode2Info info) {
        add_Group.setVisibility(View.GONE);
        yg_list.addData(info.getDrug());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Looper.getMainLooper().getQueue().addIdleHandler(new MessageQueue.IdleHandler() {
                @Override
                public boolean queueIdle() {
                    ns_view.fullScroll(NestedScrollView.FOCUS_DOWN);
                    return false;
                }
            });
        }
    }

    @Override
    public void showSuccess() {
        showTip("赠药成功");
        finish();
    }

    @Override
    public void signQrCode(int patientId) {
       Bundle b = new Bundle();
        b.putInt("patientId",patientId);
        b.putInt("type",2);
        showActivityForResult(SignQrCodeActivity.class, b, Constants.SIGN_NEXT);
    }

    private void setDrugData(List<CouponDrug.ListDTO> list) {
        int all = 0;
        for (CouponDrug.ListDTO cpreSendDrug : list) {
            View itemView = LayoutInflater.from(mContext).inflate(R.layout.drug_span_item, null);
            TextView tv_name = (TextView) itemView.findViewById(R.id.tv_name);
            TextView tv_he = (TextView) itemView.findViewById(R.id.tv_he);
            tv_name.setText(cpreSendDrug.getName());
            tv_he.setText(cpreSendDrug.getQuantity() + "");
            all += cpreSendDrug.getQuantity();
            lin_add_drugs.addView(itemView);
        }
        tv_he.setText(all + "");
    }


    @OnClick({R.id.img_back, R.id.lin_already_scan, R.id.tv_end_confim, R.id.ll_yymc,R.id.ll_tel_type,R.id.ll_credit_type})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.lin_already_scan://
                Bundle b = new Bundle();
                b.putInt("type", CaptureActivity.TYPE_RE);
                b.putString("title", getString(R.string.gajhsm));
                showActivityForResult(CaptureActivity.class, b, Constants.RESULT_CAPTER);
                break;
            case R.id.tv_end_confim:
                if (!isConfirm) {
                    showTip("请先关爱计划扫码");
                    return;
                }
                if (TextUtils.isEmpty(et_name.getText().toString())) {
                    showTip("请填写患者姓名");
                    return;
                }

                if (TextUtils.isEmpty(et_tel.getText())) {
                    showTip("请填写患者联系方式");
                    return;
                }

                if (telType == 0 && et_tel.getText().toString().length() !=11) {
                    showTip("请正确填写患者手机号码");
                    return;
                }
                if (telType == 1 && !et_tel.getText().toString().contains("-")) {
                    showTip("请正确填写患者固定电话");
                    return;
                }
                if (TextUtils.isEmpty(et_idcard.getText())) {
                    showTip("请填写患者证件号");
                    return;
                }


                if (creditType == 0 && et_idcard.getText().length() != 18) {
                    showTip("请填写患者身份证号");
                    return;
                }
                if (TextUtils.isEmpty(et_jzys.getText().toString())) {
                    showTip("请填写就诊医生");
                    return;
                }
                if (TextUtils.isEmpty(tv_yymc.getText().toString()) || "请选择".equalsIgnoreCase(tv_yymc.getText().toString())) {
                    showTip("请选择医院");
                    return;
                }
                if (TextUtils.isEmpty(et_name.getText().toString())) {
                    showTip("请填写患者姓名");
                    return;
                }

//                if (mPresent.getResultData().getUsestatus() == 1) {
//                    if ()
//                }


                final CouponDrug drugCodeInfo = new CouponDrug();
                drugCodeInfo.setCouponcode(mPresent.getResultData().getCouponcode());
                drugCodeInfo.setDoctorname(et_jzys.getText().toString());
                drugCodeInfo.setHospitalid(mPresent.getHospitalid());
                drugCodeInfo.setIdcardnum(et_idcard.getText().toString());
                drugCodeInfo.setPhonenum(et_tel.getText().toString());
                drugCodeInfo.setTruename(et_name.getText().toString());
                Map<String, List<DrugCodeItem>> infos = yg_list.getDatas();
                if (infos.isEmpty()) {
                    showTip("请赠药扫码");
                    return;
                }
                int count = 0;
                final StringBuffer stringBuffer = new StringBuffer();
                Set<Map.Entry<String, List<DrugCodeItem>>> entries = infos.entrySet();
                for (Map.Entry<String, List<DrugCodeItem>> entry : entries) {
                    List<DrugCodeItem> value = entry.getValue();
                    for (DrugCodeItem drugDTO : value) {
                        count += 1;
                        stringBuffer.append(drugDTO.getDrugcode()).append(",");
                    }
                }
                stringBuffer.deleteCharAt(stringBuffer.length() - 1);
                final StringBuffer pics = new StringBuffer();
                if (imgUrl.size() > 0) {
                    for (int i = 0; i < imgUrl.size(); i++) {
                        pics.append(imgUrl.get(i)).append(",");
                    }
                    pics.deleteCharAt(pics.length()-1);
                }

                if (mPresent.getResultData().getDrugtotal() == count) {
                    mPresent.addcoupondrugpresent(drugCodeInfo, stringBuffer.toString(), pics.toString(),creditType);
                } else
                    DialogUtils.showCountDialogTip(this, mPresent.getResultData().getDrugtotal(), count, new DialogListener() {
                        @Override
                        public void onCancl(Dialog dialog) {
                            dialog.cancel();
                        }

                        @Override
                        public void onConfirm(Dialog dialog) {
                            dialog.cancel();
                            mPresent.addcoupondrugpresent(drugCodeInfo, stringBuffer.toString(), pics.toString(),creditType);
                        }
                    });

                break;
            case R.id.ll_yymc:
                b = new Bundle();
                showActivityForResult(HospitalActivity.class, b, Constants.HOSPITAL_TYPE);
                break;
            case R.id.ll_tel_type:
                b = new Bundle();
                b.putInt("type", 1);
                showActivityForResult(CommonListActivity.class, b, Constants.RESULT_TEL_TYPE);
                break;
            case R.id.ll_credit_type:
                b = new Bundle();
                b.putInt("type", 0);
                showActivityForResult(CommonListActivity.class, b, Constants.RESULT_CRIDET_TYPE);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i(AlreadyDrugGiveActivity.class.getName(), "#########requestCode:" + requestCode + ";######resultCode:" + resultCode);
        if (resultCode == RESULT_OK && requestCode == Constants.RESULT_CAPTER) {
            String code = data.getStringExtra("code");
            Log.i(TAG, "---" + code);
            if (TextUtils.isEmpty(code)) {
                showTip("扫码返回的数据不正确,请重新扫码");
                return;
            }
            if (!isConfirm)
                mPresent.querycouponcode(code);
            else {
                if (yg_list.isContains(code)) {
                    showTip("你扫入的监管码已重复，请检查");
                } else
                    mPresent.querydruginfo(code);
            }

        } else if (requestCode == Constants.HOSPITAL_TYPE && resultCode == RESULT_OK) {//选择医院
            Bundle bundle = data.getExtras();
            if (null != bundle) {
                if (bundle.containsKey("hospitalBean")) {
                    HospitalBean hospitalBean = (HospitalBean) bundle.getSerializable("hospitalBean");
                    tv_yymc.setText(hospitalBean.getHospitalname());
                    mPresent.setHospitalid(hospitalBean.getHospitalid());
                }
            }

        } else if ((requestCode == CameraUtil.PHOTO_PICKED_WITH_DATA ||
                requestCode == CameraUtil.CAMERA_WITH_DATA ||
                requestCode == CameraUtil.CAMERA_COMPLETE) && resultCode == RESULT_OK) {//获取照片

            GetPhotoFromAlbum.GetPhoto(CarePlanActivity.this, requestCode, data, false, mPhotoCallBack);

        } else if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {

            obtainPathResult.addAll(Matisse.obtainPathResult(data));

            updateImg(Matisse.obtainPathResult(data));

        }else if(resultCode == RESULT_OK && requestCode == Constants.RESULT_TEL_TYPE){
            String key = data.getStringExtra("key");
            tv_tel_type.setText(key);
            telType = data.getIntExtra("value",0);
        } else if (resultCode == RESULT_OK && requestCode == Constants.RESULT_CRIDET_TYPE){
            String key = data.getStringExtra("key");
            tv_crdeit_type.setText(key);
            creditType = data.getIntExtra("value",0);
        }
        else if (resultCode == RESULT_OK && requestCode == Constants.SIGN_NEXT){
            int signStatus = data.getIntExtra("status",-99);
            if(signStatus == SignStatusEnum.YQ.getType()){
                tv_sign_status.setText(SignStatusEnum.YQ.getName());
                tv_sign_status.setTextColor(getResources().getColor(SignStatusEnum.YQ.getColor()));
            }else {
                showTip("订单未提交成功");
            }
        }

    }

    private ProgressDialog dialog;

    private void updateImg(List<String> obtainPathResult) {
        dialog = new ProgressDialog(mContext, R.style.myDialogTheme);
        dialog.show();
        View layout = View.inflate(mContext, R.layout.progress, null);
        TextView tv_tip = (TextView) layout.findViewById(R.id.tv_tip);
        tv_tip.setText(R.string.zzsc);
        dialog.setContentView(layout);
        Window win = dialog.getWindow();
        win.setGravity(Gravity.CENTER);
        // 弹出对话框时，底部窗体，不变暗。
        WindowManager.LayoutParams lp = win.getAttributes();
        lp.width = (int) (MyApplication.widthPixels * 0.85);
        win.setAttributes(lp);
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);

        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                    if (null != dialog) {
                        dialog.dismiss();
                        return true;
                    }
                }
                return false;
            }
        });

        GetPhotoFromAlbum.compressImageByQualityList(obtainPathResult, mContext, iHandler);
    }

    PhotoCallBack mPhotoCallBack = new PhotoCallBack() {
        @Override
        public void Success(final String path) {
            Log.i("fancl", "-----path" + path);
            GetPhotoFromAlbum.compressImageByQuality(path, CarePlanActivity.this, iHandler);//压缩图片

        }

        @Override
        public void Failed(String errormsg) {
            showTip("失败" + errormsg);
        }
    };


    @Override
    public void showTip(String msg) {
        super.showTip(msg);
    }

    @Override
    public void setPresenter(CarePlanContract.Present presenter) {

    }

    /**
     * 处理接收消息
     */
    private void addMessageHandler() {
        iHandler = new Handler() {
            public void handleMessage(Message msg) {
                try {
                    switch (msg.what) {
                        case Constants.UploadSuccess://阿里云上传图片成功
                            Image img = (Image) msg.obj;
                            //members.setHeadpicpath(img.getImagepath());

//                            shdurl = img.getImagepath();
//                            Log.i("swt", "shdurl = " + shdurl);
                            imgUrl.add(img.getImagepath());
                            if (imgUrl.size() == obtainPathResult.size()) {
                                dialog.dismiss();
                                storeAdapter.setData(imgUrl);
                            }

                            //                            img_shd.setImageBitmap(CameraUtil.fitSizeImg(localUrl));


                            break;

                        case Constants.UploadFailed://阿里云上传图片失败
                            //                            members.setHeadpicpath("");
                            //shdurl = "";
                            //                            img_shd.setImageResource(R.drawable.photograph_icon);
                            dialog.dismiss();
                            showTip("上传图片失败");
                            break;
                        case 100://开始阿里云上传
                            //shdurl = "";
                            //                            img_shd.setImageResource(R.drawable.photograph_icon);

                            //showTip("开始上传图片");
                            localUrl = (String) msg.obj;
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    new PutAliyObject(MyApplication.oss, Constants.imgBucket, Utils.getOKey2(), localUrl, iHandler).asyncPutObjectFromLocalFile();
                                }
                            }).start();
                            break;

                        default:

                            break;
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    Log.e("error.store", e.toString());
                }
                super.handleMessage(msg);
            }
        };
    }
}
